package com.kl.mq;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kl.domain.LogisticsStoreDTO;
import com.kl.em.Result;
import com.kl.entity.CityOrder;
import com.kl.feign.LogisticsStoreControllerFeign;
import com.kl.feign.SameCityServiceFeign;
import com.kl.feign.StaffServiceFeign;
import com.kl.service.ICityOrderService;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@RocketMQMessageListener(consumerGroup = "samecity-consumer", topic = "kulunwuliu-samecity")
@Component
public class SameCityMq implements RocketMQListener<String> {

    @Autowired
    private ICityOrderService cityOrderService;
    @Autowired
    private LogisticsStoreControllerFeign logisticsStoreControllerFeign;
    @Autowired
    private StaffServiceFeign staffServiceFeign;
    @Autowired
    private SameCityServiceFeign sameCityServiceFeign;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void onMessage(String s) {
        System.out.println("进入mq");
        CityOrder cityOrder = cityOrderService.getById(s);
        //先判断是否有送货员接单
        if (cityOrder.getMeetStatus() == 0){
            String spare = cityOrder.getSpare(); //获取发布订单所在的城市
            //通过城市查询站点
            Result<List<LogisticsStoreDTO>> listResult = logisticsStoreControllerFeign.selectByCityId(spare);
            System.out.println(listResult.getMessage());
            List<LogisticsStoreDTO> logList = listResult.getResult();//所有站点
            System.out.println(logList);
            List<Long> siteIdList = null;
            //先拿到站点id，再获取站点中的所有员工s
            for (int i = 0; i < logList.size(); i++) {
                Long siteId = logList.get(i).getId();
                siteIdList.add(siteId);//站点id
            }
            //通过站点id拿到同城的送货员
            Result<List<Long>> resultList = staffServiceFeign.findSameCityStaff(siteIdList);
            List<Long> staffIdList = resultList.getResult();
            Random random = new Random();
            int i = random.nextInt(staffIdList.size());
            Long id = staffIdList.get(i);
            Result result = sameCityServiceFeign.updateConsigneeBySuccess(cityOrder.getId(), id);
            System.out.println(result.getMessage());
            redisTemplate.delete(id);
            System.out.println("mq执行成功");
        }
    }
}
